﻿using System.Collections.Generic;

namespace Raven
{
    public class GraveRecord : BaseGameEntity
    {
        private Fix _timeCreated;
        private DisplayObject _displayObject;
        private GraveMarkers _graveMarkers;

        public GraveRecord(Fix timeCreated, Vector2 pos):base(Raven.EntityType.Grave)
        {
            _position = pos;
            _timeCreated = timeCreated;
            CreateDisplayObject();
        }

        public Fix TimeCreated => _timeCreated;

        public override void Destroy()
        {
            _displayObject.Destroy();
            _displayObject = null;
        }

        public void CreateDisplayObject()
        {
            _displayObject = DisplayObjectFactory.CreateDisplayObject(this);
            _displayObject.Start();
        }
    }

    public class GraveMarkers
    {
        private Fix _lifeTime;
        private RavenGame _world;
        private LinkedList<GraveRecord> GraveList;

        public GraveMarkers(RavenGame world, int graveLifetime)
        {
            _world = world;
            _lifeTime = graveLifetime;
            GraveList = new LinkedList<GraveRecord>();
        }

        public void Update()
        {
            var current = GraveList.First;
            while (current != null)
            {
                GraveRecord grave = current.Value;
                if (_world.GetTimer().currentTime - grave.TimeCreated > _lifeTime)
                {
                    grave.Destroy();
                    var n = current;
                    GraveList.Remove(current);
                }
                current = current.Next;
            }
        }

        public void AddGrave(Vector2 pos)
        {
            GraveList.AddLast(new GraveRecord(_world.GetTimer().currentTime, pos));
        }

        public void Reset()
        {
            var current = GraveList.First;
            while (current != null)
            {
                GraveRecord grave = current.Value;
                grave.Destroy();
                GraveList.Remove(current);
                current = current.Next;
            }
        }
    }
}